<template>

  <div>
    <el-divider></el-divider>
    <!--操作按钮-->
    <div>
      <div style="display: flex;justify-content: space-between">
        <div>
          <el-input v-model="text" style="width: 300px;margin-right: 10px;"
                    size="small" placeholder="请输入学生姓名、登录账号、地址" clearable @clear="initTable">
          </el-input>
          <el-button type="primary" @click="textPage(text)" icon="el-icon-search"
                     size="small" style="width: 90px;">搜索
          </el-button>
        </div>
        <div>
          <el-button type="primary" plain @click="thenAdd()" icon="el-icon-circle-plus"
                     size="small">添加
          </el-button>
          <el-button type="danger" plain icon="el-icon-s-unfold" @click="getTemplate()"
                     size="small">模板说明
          </el-button>
          <el-button type="warning" plain icon="el-icon-milk-tea" @click="importFileCPM=true"
                     size="small">批量导入
          </el-button>
          <el-button type="info" plain icon="el-icon-reading" @click="initErrPageTable()"
                     size="small">导入记录
          </el-button>
          <el-button type="danger" @click="idsDelete(ids)" icon="el-icon-delete"
                     :disabled="ids.length===0" size="small">批量删除
          </el-button>
        </div>
      </div>
    </div>
    <!--分页列表-->
    <div class="tableSet">
      <!--handleSelectionChange 复选框点击事件，就是每一条数据前面的勾选按钮-->
      <el-table
          border
          ref="multipleTable"
          :data="page.data"
          tooltip-effect="dark"
          style="width: 100%"
          size="small"
          @selection-change="handleSelectionChange"
          v-loading="loading">
        <el-table-column
            type="selection"
            width="55">
        </el-table-column>
        <el-table-column
            prop="id"
            label="编号"
            width="50">
        </el-table-column>
        <el-table-column
            prop="name"
            label="学生姓名"
            width="200">
        </el-table-column>
        <el-table-column
            prop="username"
            label="登录账号"
            width="150"
            show-overflow-tooltip>
        </el-table-column>
        <el-table-column
            prop="teacher"
            label="角色"
            width="50"
            show-overflow-tooltip>
          <template slot-scope="scope">
            {{ scope.row.teacher === true ? '教师' : '学生' }}
          </template>
        </el-table-column>
        <el-table-column
            prop="phone"
            label="电话"
            width="150"
            show-overflow-tooltip>
        </el-table-column>
        <el-table-column
            prop="address"
            label="地址"
            width="200"
            show-overflow-tooltip>
        </el-table-column>
        <el-table-column
            prop="enabled"
            label="状态"
            width="50"
            show-overflow-tooltip>
          <template slot-scope="scope">
            <el-switch
                v-model="scope.row.enabled"
                active-color="#13ce66"
                inactive-color="#ff4949" @oc>
            </el-switch>
            {{ scope.row.enabled === true ? '启用' : '禁用' }}
          </template>
        </el-table-column>
        <el-table-column
            prop="password"
            label="密码"
            width="50"
            show-overflow-tooltip>
        </el-table-column>
        <el-table-column
            prop="userFace"
            label="头像地址"
            width="300"
            show-overflow-tooltip>
        </el-table-column>
        <el-table-column
            label="操作"
            show-overflow-tooltip>
          <template slot-scope="scope">
            <!--$index 下标，row 行数据-->
            <el-button
                size="mini"
                @click="thenUpdate(scope.$index, scope.row)">编辑
            </el-button>
            <!-- type="danger" 删除按钮红色-->
            <el-button
                size="mini"
                type="danger"
                @click="thenDelete(scope.$index, scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>


    <!--分页控制组件-->
    <div class="block">
      <!--/**
      * 当前条数，@size-change 自动带过来的
      * @param val
      */-->
      <!-- /**
     * 当前页，@current-change 自动带过来的
     */-->
      <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 40, 50, 100]"
          :page-size="size"
          layout="total, prev, pager, next, sizes, jumper"
          :total="page.total">
      </el-pagination>

    </div>

    <el-dialog
        title="导入记录:"
        width="50%"
        :before-close="handleCloseErrPage"
        :visible.sync="dialogErrPage">
      <!--分页列表-->
      <div class="tableSet">
        <!--handleSelectionChange 复选框点击事件，就是每一条数据前面的勾选按钮-->
        <el-table
            border
            ref="multipleTable"
            :data="errPage.data"
            tooltip-effect="dark"
            style="width: 100%"
            size="small"
            v-loading="loading">
          <el-table-column prop="erId" label="数据编号" width="150px"></el-table-column>
          <el-table-column prop="erText" label="错误信息" width="400px"></el-table-column>
          <el-table-column prop="erCreateTime" label="导入时间" width="262px"></el-table-column>
        </el-table>
      </div>
      <!--错误记录分页-->
      <div class="block">
        <!--/**
        * 当前条数，@size-change 自动带过来的
        * @param val
        */-->
        <!-- /**
       * 当前页，@current-change 自动带过来的
       */-->
        <el-pagination
            background
            @size-change="handleSizeChangeErrPage"
            @current-change="handleCurrentChangeErrPage"
            :current-page="errCurrentPage"
            :page-sizes="[10, 20, 30, 40, 50, 100]"
            :page-size="errSize"
            layout="total, prev, pager, next, sizes, jumper"
            :total="errPage.total">
        </el-pagination>
        <el-button style="margin-top: 10px;" @click="dialogErrPage = false">关 闭</el-button>
      </div>
    </el-dialog>
    <!--弹窗，点了编辑会先给addData中的字段赋值，因为编写需要通过id去改该条数据-->
    <div>
      <el-dialog
          :title="addData.id === 0? '添加':'编辑'"
          :visible.sync="dialogVisible"
          width="30%"
          :before-close="handleClose"
          center>
        <el-form :label-position="textAlign"
                 :model="addData" status-icon ref="ruleForm" label-width="100px" class="demo-ruleForm"
                 :rules="fromRules">
          <el-form-item label="学生姓名:" prop="name">
            <el-input style="width: 92%" v-model="addData.name" clearable></el-input>
          </el-form-item>
          <el-form-item label="登录账号:" prop="username">
            <el-input style="width: 92%" v-model="addData.username" clearable></el-input>
          </el-form-item>
          <el-form-item label="角色:">
            <el-radio v-model="addData.teacher" :label="defaultStudent" border>学生</el-radio>
            <el-radio v-model="addData.teacher" :label="defaultTeacher" border>教师</el-radio>
          </el-form-item>

          <el-form-item label="状态:">
            <el-radio v-model="addData.enabled" :label="true" border>启用</el-radio>
            <el-radio v-model="addData.enabled" :label="false" border>禁用</el-radio>
          </el-form-item>
          <el-form-item label="电话:" prop="phone">
            <el-input style="width: 92%" v-model="addData.phone" clearable></el-input>
          </el-form-item>
          <el-form-item label="头像地址:">
            <el-input style="width: 92%" v-model="addData.userFace" clearable></el-input>
          </el-form-item>
          <el-form-item label="地址:" prop="fromAddress">
            <el-input style="width: 92%" v-model="addData.address" clearable></el-input>
          </el-form-item>
          <el-form-item>
            <!--@keydown.enter.native 键盘回车触发-->
            <el-button type="primary" @click="submitForm()">提交</el-button>
            <el-button @click="cancel()">取 消</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
    <el-dialog title="上传文件" :visible.sync="importFileCPM" width="400px" @close="cancel()">
      <!--批量导入弹窗-->
      <el-upload
          ref="upload"
          action="../userAdds"
          class="upload-demo"
          :multiple="false"
          :limit="1"
          accept=".xlsx"
          :auto-upload="false"
          :headers="headers"
          :data="param"
          :on-change="handleChange"
          :on-success="success"><!--:headers="headers"-->
        <el-button size="small" type="primary">点击上传</el-button>
        <div slot="tip" class="el-upload__tip">只能上传excel文件</div>
      </el-upload>
      <div slot="footer">
        <el-button type="primary" @click="cancels">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import uploadFile from "@/components/file/upload-file";

export default {
  name: "EmpBasic",
  //导入组件
  components: {
    uploadFile
  },
  data() {
    return {
      // 错误记录弹窗
      dialogErrPage: false,
      // 导入文件弹窗
      importFileCPM: false,
      // 文件
      file: '',
      // 文件格式
      param: {
        ContentType: 'multipart/form-data'
      },
      // 文件请求头
      headers: {
        'authorization': window.sessionStorage.getItem(('tokenStr'))
      },
      defaultTeacher: true,
      defaultStudent: false,
      // 表单文字对其方式
      textAlign: 'right',
      // 加载动画
      loading: false,
      // 弹窗控制，true打开弹窗，false关闭弹窗
      dialogVisible: false,
      // 增加修改对象
      addData: {
        address: '',
        name: '',
        phone: '',
        teacher: false,
        telephone: '',
        userFace: '',
        username: '',
        enabled: true
      },
      // 批量删除数组
      deleteIds: [],
      // 分页对象
      page: {
        total: 0,
        data: [{}]
      },
      errPage: {
        total: 0,
        data: [{}]
      },
      // 第几页，默认第一页
      currentPage: 1,
      // 每页大小，默认10条数据一页
      size: 10,
      // 第几页，默认第一页
      errCurrentPage: 1,
      // 每页大小，默认10条数据一页
      errSize: 10,
      // 分页搜索文本
      text: '',
      // 表单正则校验
      fromRules: {
        name: [
          {required: true, message: '请输入姓名', trigger: 'blur'}
        ],
        username: [
          {required: true, message: '请输入账号', trigger: 'blur'}
        ],
        // fromAddress: [
        //   {required: true, message: '请输入地址', trigger: 'blur'}
        // ],
        phone: [
          {required: true, message: '请输入电话', trigger: 'blur'}
        ]
      },
      // 批量操作ids
      ids: []
    }
  },
  // 一进入页面就要调用的接口放到 mounted 里面，比如页面表格分页
  mounted() {
    this.initTable();
  },
  methods: {
    /**
     * 文本搜索
     */
    textPage(text) {
      this.text = text;
      this.initTable();
    },
    /**
     * 分页数据
     */
    initTable() {
      this.loading = true
      this.getRequestParams("/page", {currentPage: this.currentPage, size: this.size, text: this.text}).then(data => {
        if (data) {
          this.page = data
          this.loading = false;
        }
      })
    },
    initErrPageTable() {
      this.loading = true
      // 打开错误记录表格弹窗
      this.dialogErrPage = true
      this.getRequestParams("/errorRecord/page", {currentPage: this.errCurrentPage, size: this.errSize}).then(data => {
        if (data) {
          this.errPage = data
          this.loading = false;
        }
      })
    },
    /**
     * 提交表单
     */
    submitForm() {
      // 正则校验表单数据
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {// 验证通过
          if (this.addData.id === 0) {
            // 调用添加接口
            this.postRequestData('/addAdmin', this.addData).then(data => {
              // 添加成功
              if (data) {
                // 刷新表格数据
                this.initTable();
              }
            })
            // 关闭弹窗
            this.dialogVisible = false;
            this.addData = {teacher: false, enabled: true};
          } else {
            // 调用添加接口
            this.postRequestData('/addAdmin', this.addData).then(data => {
              // 修改成功
              if (data) {
                // 刷新表格数据
                this.initTable();
              }
            })
            // 关闭弹窗
            this.dialogVisible = false;
            // 默认选择按钮
            this.addData = {teacher: false, enabled: true};
          }
        } else {
          this.$message.error('请输入必填项!');
          return false;
        }
      });
    },
    /**
     * 复选框
     */
    handleSelectionChange(val) {
      this.ids = val
    },
    /**
     * 添加按钮点击事件
     */
    thenAdd() {
      this.addData = {id: 0, teacher: false, enabled: true};
      this.dialogVisible = true;
      this.$refs.ruleForm.resetFields();
    },
    /**
     * 编辑按钮点击事件
     */
    thenUpdate(index, data) {
      console.log(data)
      this.addData = {
        id: data.id,
        address: data.address,
        name: data.name,
        phone: data.phone,
        teacher: data.teacher,
        enabled: data.enabled,
        telephone: data.telephone,
        userFace: data.userFace,
        username: data.username
      };
      this.dialogVisible = true;
    },
    /**
     * 删除点击事件
     */
    thenDelete(index, data) {
      console.log(data)
      this.$confirm('确定删除此记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 调用删除接口
        this.postRequestParams('/deleteAdmin', {id: data.id}).then(res => {
          if (res) {
            // 刷新表格
            this.initTable();
          }
        })
      }).catch(() => {
        this.$message({
          type: 'error',
          message: '已取消'
        });
      });

    },
    /**
     * 批量删除
     */
    idsDelete(ids) {
      console.log(ids)
      this.$confirm('此操作将永久删除[' + this.ids.length + ']记录！, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let x = [];
        for (let item of ids) {
          x.push(item.id);
        }
        // 调用删除接口
        this.postRequestData('/deleteAdmins', x).then(res => {
          if (res) {
            // 刷新表格
            this.initTable();
          }
        })
      }).catch(() => {
        this.$message({
          type: 'success',
          message: '已取消'
        });
      });
    },
    /**
     * 取消
     */
    cancel() {
      // 关闭弹窗
      this.dialogVisible = false;
      // 初始化
      this.addData = {teacher: false, enabled: true};
    },
    /**
     * 关闭弹窗
     * @param done
     */
    handleClose(done) {
      this.$confirm('确认关闭？')
          .then(_ => {// 确定关闭
            // 初始化
            this.addData = {teacher: false, enabled: true};
            // 清除表单校验
            this.$refs.ruleForm.resetFields();
            done();
          })
          .catch(_ => {// 不关闭弹窗

          });
    },
    handleCloseErrPage() {
      this.$confirm('确认关闭？')
          .then(_ => {// 确定关闭
            this.dialogErrPage = false
            done();
          })
          .catch(_ => {// 不关闭弹窗

          });
    },
    /**
     * val 这个是当前页，@current-change 自动带过来的
     */
    handleCurrentChange(val) {
      this.currentPage = val;
      this.initTable();
    },
    /**
     * val 这个是当前条数，@size-change 自动带过来的
     * @param val
     */
    handleSizeChange(val) {
      this.size = val;
      this.initTable();
    },
    handleCurrentChangeErrPage(val) {
      this.errCurrentPage = val;
      this.initErrPageTable();
    },
    /**
     * val 这个是当前条数，@size-change 自动带过来的
     * @param val
     */
    handleSizeChangeErrPage(val) {
      this.size = val;
      this.initErrPageTable();
    },
    handleChange(file, fileList) {
      if (file) {
        if (file.name.indexOf('xlsx') !== -1) {
          this.file = file
        } else {
          this.$message({
            message: '请上传xlsx格式的文件！',
            type: 'warning'
          });
        }
      }
    },
    openUploadFile(val) {
      this.param.type = val
      this.importFileCPM = true
    },
    cancels() {
      // 参数类型
      this.param.type = ''
      // 关闭弹窗
      this.importFileCPM = false
      // 清理文件
      this.$refs.upload.clearFiles()
    },
    submit() {
      if (this.file) {
        // 提交文件
        this.$refs.upload.submit();
        // 关闭弹窗
        this.importFileCPM = false
        // 刷新列表
        this.initTabl()
      } else {
        this.$message({
          message: '请上传xlsx格式的文件！',
          type: 'warning'
        });
      }
    },
    success(response, file, fileList) {
      console.log(response)
      if (!response.status) {
        this.$message({
          message: response.message,
          type: 'success',
          duration: 3000
        });
      } else {
        let data = response.data
        const context = []
        const h = this.$createElement
        context.push(h('p', null, '导入成功：' + data.successRow + '条'))
        context.push(h('p', null, '导入失败：' + data.errorRow.length + '条'))
        if (data.errorRow.length > 0) {
          context.push(h('p', null, '失败：'))
          const errorRow = []
          for (let item of data.errorRow) {
            errorRow.push(h('p', null, item))
          }
          context.push(h('div', {
            style: {
              maxHeight: '300px',
              overflow: 'auto'
            }
          }, errorRow))
        }
        this.$confirm(h('div', null, context), '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.cancel()
          this.$emit('loadTable', 1)
        }).catch(() => {
          this.cancel()
          this.$emit('loadTable', 1)
        })
      }

    },
    /**
     * 获取模板文件
     */
    getTemplate() {
      this.postRequestData("/getTemplate").then(data => {
        if (data) {
          console.log(data)
          let a = document.createElement('a')
          a.download = ''
          a.href = data.obj
          a.click()
        }
      })
    },
    /**
     * 获取错误记录分页
     */
    getErrorRecordPage() {

    }


  }

}
</script>

<style scoped>

.tableSet {
  margin-top: 10px;
}

.block {
  margin-top: 10px;
  text-align: center;
}


</style>